<template>
  <el-form
    ref="formRef"
    :inline="props.inline"
    :label-width="labelWidth"
  >
    <el-row>
      <el-col
        :span="8"
        v-for="(item, index) in props.formItems"
        :key="index"
      >
        <el-form-item
          :label="item.label"
          :prop="item.prop"
          :label-width="item.labelWidth"
        >
          <el-date-picker
            v-if="item.type == FormItemTypeEnum.date"
            v-model="form[item.prop]"
            :placeholder="item.placeholder"
            type="date"
          >
          </el-date-picker>
          <el-select
            v-else-if="item.type == FormItemTypeEnum.select"
            v-model="form[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable"
          >
            <el-option
              v-for="it in item.options"
              :key="it.value"
              :label="it.label"
              :value="it.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-else-if="item.type == FormItemTypeEnum.textArea"
            v-model="form[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable"
            type="textarea"
            autosize
          ></el-input>
          <el-input
            v-else
            v-model="form[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script setup lang="ts">
import { Ref, onMounted, ref, watch, PropType } from 'vue'
import FormItemModel from '@/model/FormItemModel'
import FormItemTypeEnum from '@/model/enums/FormItemTypeEnum'

let props = defineProps({
  inline: {
    type: Boolean,
    default: false,
  },
  labelWidth: {
    type: String,
    default: '80px',
  },
  formItems: {
    type: Array as PropType<Array<FormItemModel>>,
    required: true,
    default: (): Array<FormItemModel> => [],
    validator: function (value: Array<any>) {
      if (value && value.length > 0) {
        const f = value.every((item) => item instanceof FormItemModel)
        if (!f) console.warn('formItems参数格式不对！必须是Array<FormItemModel>类型')
        return f
      }
      console.warn('formItems是必须的')
      return false
    },
  },
})
let form: Ref<any> = ref({})
onMounted(() => {
  initForm(props.formItems as Array<FormItemModel>)
})
watch(
  () => props.formItems as Array<FormItemModel>,
  (newV: FormItemModel[]) => {
    initForm(newV)
  }
)
let initForm = (items: FormItemModel[]) => {
  for (let item of items) {
    form.value[item.prop] = ''
  }
}
</script>
